const {
  fileUploadError,
  unSupportedFileType,
  publishGoodsError,
  invalidGoodsID,
  internalServerError
} = require("../constant/error");
const path = require("path");
const {
  createGoods,
  updateGoods,
  removeGoods,
  restoreGoods,
  findGoods,
  searchGoods
} = require("../service/goodsService");
class GoodsController {
  async upload(ctx, next) {
    const file = ctx.request.files.file;
    const fileType = ["image/jpeg", "image/png", "image/jpg"];
    if (file) {
      if (!fileType.includes(file.mimetype)) {
        return ctx.app.emit("error", unSupportedFileType, ctx);
      }
      ctx.body = {
        code: 0,
        msg: "图片上传成功",
        result: {
          img: path.basename(file.filepath),
        },
      };
    } else {
      return ctx.app.emit("error", fileUploadError, ctx);
    }
  }

  async create(ctx, next) {
    try {
      const { createdAt, updatedAt, ...res } = await createGoods(
        ctx.request.body
      );
      ctx.body = {
        code: 0,
        msg: "商品发布成功",
        result: res,
      };
    } catch (err) {
      console.error(err)
      return ctx.app.emit("error", publishGoodsError, ctx);
    }
  }

  async update(ctx, next) {
    try {
      const res = await updateGoods(ctx.params.id, ctx.request.body);
      if (res) {
        ctx.body = {
          code: 0,
          msg: "商品更新成功",
          result: res,
        };
      } else {
        return ctx.app.emit("error", invalidGoodsID, ctx);
      }
    } catch (err) {
      return ctx.app.emit("error", publishGoodsError, ctx);
    }
  }

  async remove(ctx, next) {
    const res = await removeGoods(ctx.params.id);
    if (res) {
      ctx.body = {
        code: 0,
        msg: "商品下架成功",
        result: "",
      }
    }
    else{
      return ctx.app.emit("error", invalidGoodsID, ctx);
    }
  }

  async restore(ctx, next){
    const res = await restoreGoods(ctx.params.id)
    if(res){
      ctx.body = {
        code: 0,
        msg: "商品上架成功",
        result: "",
      }
    }
    else{
      return ctx.app.emit("error", invalidGoodsID, ctx);
    }
  }
  
  async findAll(ctx){
    const {pageNum=1, pageSize=10} = ctx.request.query
    const res = await findGoods(pageNum, pageSize)
    ctx.body = {
      code: 0,
      msg: "获取商品列表成功",
      result: res,
    }
  }
  async search(ctx){
    try {
      const { keyword, pageNum = 1, pageSize = 10 } = ctx.request.query;
      const res = await searchGoods(pageNum, pageSize, keyword);
      ctx.body = {
          code: 0,
          msg: "搜索商品成功",
          result: res,
      };
  } catch (error) {
      console.error(error)
      return ctx.app.emit("error", internalServerError, ctx);
    }
  }
}

module.exports = new GoodsController();
